﻿using System;
using System.Collections.Generic;

namespace JTLeigh.Commerce.Spencer.Features.ProductFeedback.Business
{

	/// <summary>
	/// Counter used to calculate the average of a series of values for a collection of attributes.
	/// </summary>
	public class AttributeAveragingCounter
	{

		#region Fields

		private Dictionary<Guid, AveragingCounter> _counters;

		#endregion // Fields

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="AttributeAveragingCounter"/> class.
		/// </summary>
		public AttributeAveragingCounter()
		{
			_counters = new Dictionary<Guid, AveragingCounter>();
		}

		#endregion // Constructors

		#region Properties

		/// <summary>
		/// Gets the averages of the values that have been added for each attribute.
		/// </summary>
		/// <value>A <see cref="Dictionary{TKey, TValue}"/> containing the average of each value 
		/// that has been added for each attribute, keyed by the attribute identifier.</value>
		public Dictionary<Guid, double> Averages
		{
			get
			{
				Dictionary<Guid, double> averages;

				averages = new Dictionary<Guid, double>(_counters.Count);
				foreach (KeyValuePair<Guid, AveragingCounter> counter in _counters)
				{
					if (counter.Value.Average.HasValue)
					{
						averages.Add(counter.Key, counter.Value.Average.Value);
					}
				}
				return averages;
			}
		}

		#endregion // Properties

		#region Methods

		/// <summary>
		/// Adds a value for an attribute.
		/// </summary>
		/// <param name="attributeId">The attribute identifier <see cref="Guid"/> of the attribute 
		/// add the value for.</param>
		/// <param name="value">The <see cref="Byte"/> value to add.</param>
		public void AddValue(Guid attributeId, byte value)
		{
			AveragingCounter counter;

			if (!_counters.TryGetValue(attributeId, out counter))
			{
				counter = new AveragingCounter();
				_counters.Add(attributeId, counter);
			}
			counter.AddValue(value);
		}

		/// <summary>
		/// Resets the counter.
		/// </summary>
		public void Reset()
		{
			_counters = new Dictionary<Guid, AveragingCounter>();
		}

		#endregion // Methods

	}

}
